package com.android.aishangauction.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.aishangauction.R;
import com.android.aishangauction.activity.mine.DirectBuyPayOrderActivity1;
import com.android.aishangauction.activity.mine.LoginActivity;
import com.android.aishangauction.adapt.BaseFragmentAdapter;
import com.android.aishangauction.adapt.GridDirectBuyGoodsDetaillikeAdapt;
import com.android.aishangauction.app.BaseActivity;
import com.android.aishangauction.fragment.BaseLazyFragment;
import com.android.aishangauction.fragment.detail.Fragment_Detail_DirectBuy_GoodsDetail_Comment;
import com.android.aishangauction.fragment.detail.Fragment_Detail_GoodsDetail_DetailWeb;
import com.android.aishangauction.fragment.detail.Fragment_DirectBuy_GoodsDetail_DetailWeb;
import com.android.aishangauction.model.detail.DirectBuyGoodsDetail;
import com.android.aishangauction.model.detail.DirectBuyGoodsDetailCallback;
import com.android.aishangauction.model.detail.MainDetail;
import com.android.aishangauction.utils.CommonUtils;
import com.android.aishangauction.utils.ConstantsUrl;
import com.android.aishangauction.utils.HttpUtils;
import com.android.aishangauction.utils.LoginState;
import com.android.aishangauction.utils.MyLog;
import com.android.aishangauction.utils.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 直购商品详情
 */
public class DirectBuyGoodsDetailActivity extends BaseActivity {
    @BindView(R.id.detail_bottom_buy)
    LinearLayout detailBottomBuy;
    @BindView(R.id.detail_bottom_shouwan_tv)
    TextView detailBottomShouwanTv;
    @BindView(R.id.detail_bottom_shouwan)
    LinearLayout detailBottomShouwan;
    @BindView(R.id.click_resetnetwork_msg)
    TextView clickResetnetworkMsg;
    @BindView(R.id.click_resetnetwork_refresh)
    TextView clickResetnetworkRefresh;
    @BindView(R.id.no_data_img)
    ImageView noDataImg;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;

    @BindView(R.id.pager)
    ViewPager pager;
    @BindView(R.id.detail_title)
    TextView detailTitle;
    @BindView(R.id.title_type)
    TextView titleType;
//    @BindView(R.id.detail_like_grid)
//    MyGridView detailLikeGrid;
//    @BindView(R.id.close)
//    ImageView close;
//    @BindView(R.id.top)
//    ImageView top;
    @BindView(R.id.indicator)
    TextView indicator;

//    @BindView(R.id.detail_webView)
//    WebView detailWebView;
    @BindView(R.id.banner)
    RelativeLayout banner;
    @BindView(R.id.store_logo)
    ImageView storeLogo;
    @BindView(R.id.store_name)
    TextView storeName;
    @BindView(R.id.store_msg)
    LinearLayout storeMsg;
//    @BindView(R.id.scroll)
//    ScrollView scroll;
    @BindView(R.id.direct_goods_detail_money)
    TextView singleMoney;
    @BindView(R.id.goods_list_item_add)
    TextView goods_list_item_add;
    @BindView(R.id.direct_goods_detail_score)
    TextView singleScore;
    @BindView(R.id.direct_goods_detail_bottom_score)
    TextView totalScore;
    @BindView(R.id.direct_goods_detail_bottom_money)
    TextView totalMoney;
    @BindView(R.id.tv_tab_goods_detail)
    TextView tvTabDetail;
    @BindView(R.id.tv_tab_comment)
    TextView tvTabComment;
    @BindView(R.id.rl_tab_goods_detail)
    RelativeLayout tabDetail;
    @BindView(R.id.rl_tab_comment)
    RelativeLayout tabComment;
    @BindView(R.id.line_tab_goods_detail)
    View lineTabDetail;
    @BindView(R.id.line_tab_comment)
    View lineTabComment;
    @BindView(R.id.viewpager)
    ViewPager mViewPager;
//    @BindView(R.id.ll_bottom_like_desc)
//    LinearLayout llLike;

    private DirectBuyGoodsDetailActivity mcontext;
    private boolean networkConnected;
    private String detailid;
    private String spec = "";
    private String num = "1";
    private DirectBuyGoodsDetail mInfo;
    public RelativeLayout progress;
    public LinearLayout clickResetnetwork;

    private List<MainDetail.DataBean.GoodsItemBean> goodsItemBeen;
    private int type;
    private String common_id = "";
    private int goods_id;
    private String bid;
    private String option = "";
    private String shareurl;
    private String sharethumb;
    private String sharecontent;
    private int join_common_id = 0;
    private ArrayList<DirectBuyGoodsDetail.DataBean.ThumbsBean> Banner = new ArrayList<>();
    private GridDirectBuyGoodsDetaillikeAdapt adapter_like;
    private BannerAdapt adapter_banner;
    private String storeid;
    private Fragment_DirectBuy_GoodsDetail_DetailWeb fragment1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_direct_buy_detail_goods_b);
        ButterKnife.bind(this);
        mcontext = DirectBuyGoodsDetailActivity.this;
        initUI();
        GetDetail(detailid);
//        GetDataListData("&typeid=1");
    }

    private void initBanner() {
        adapter_banner = new BannerAdapt();
        pager.setAdapter(adapter_banner);
        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                CharSequence text = getString(R.string.viewpager_indicator,
                        position + 1, pager.getAdapter().getCount());
                indicator.setText(text);
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private class BannerAdapt extends PagerAdapter {

        @Override
        public int getCount() {
            return Banner.size();
        }


        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = getLayoutInflater().inflate(R.layout.item_fragment_banner, null);
            ImageView photoview = (ImageView) view.findViewById(R.id.imageView1);
            ObjectUtils.photo2(mcontext, Banner.get(position).getSrc(), photoview);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    private void initUI() {
        ObjectUtils.StatusBarWhiteBg(mcontext, false);
//        scroll.smoothScrollTo(0, 0);
        pager.setFocusable(true);
        pager.setFocusableInTouchMode(true);
        pager.requestFocus();
        progress = (RelativeLayout) findViewById(R.id.progress);
        clickResetnetwork = (LinearLayout) findViewById(R.id.click_resetnetwork);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        detailid = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ID);
//        common_id = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_COMMON_ID);
//        WebSettings settings = detailWebView.getSettings();
//        settings.setJavaScriptEnabled(true);
//        detailWebView.setWebChromeClient(new MyWebChromeClient());
//        detailWebView.setWebViewClient(new MyWebViewClient());
//        detailLikeGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                ToDetailActivity(mInfo.getData().getTj_list().get(position).getId());
//            }
//        });
        initBanner();
    }

//    public void ToDetailActivity(String id) {
//        Intent intent = new Intent(mcontext, DirectBuyGoodsDetailActivity.class);
//        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ID, id);
//        startActivity(intent);
//    }

    @OnClick({R.id.detail_bottom_buy,R.id.click_resetnetwork_refresh, R.id.main_top_back, R.id.main_top_right
            ,R.id.detail_bottom_shouwan, R.id.store_in, R.id.store_msg,R.id.rl_tab_comment, R.id.rl_tab_goods_detail})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.detail_bottom_shouwan:
            case R.id.detail_bottom_kai_pintuan_finish:
                return;
            case R.id.detail_bottom_buy:
                if (LoginState.getInstance().isLogin(mcontext)) {
                    ToPay(type, 2);
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
                break;
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                GetDetail(detailid);
                break;
            case R.id.main_top_back:
                finish();
                break;
//            case R.id.main_top_right:
//                Intent share = new Intent(mcontext, TransparentActivity.class);
//                share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TYPE, 1);
//                share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TITLE, "拼更多~" + sharecontent);
//                share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_CONTENT, "这么划算真的不来抢吗");
//                share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_IMAGEURL, sharethumb);
//                share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_LINK, shareurl);
//                mcontext.startActivity(share);
//                break;
            case R.id.store_in:
            case R.id.store_msg:
                Intent intent = new Intent(mcontext, GoodsStoreActivity.class);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_STORE_ID, storeid + "");
                startActivity(intent);
                break;
            case R.id.close:
                mcontext.finish();
                break;
            case R.id.top:
//                scroll.smoothScrollTo(0, 0);
                break;
            case R.id.rl_tab_goods_detail:
                tvTabDetail.setTextColor(Color.RED);
                tvTabComment.setTextColor(Color.BLACK);
                lineTabDetail.setVisibility(View.VISIBLE);
                lineTabComment.setVisibility(View.INVISIBLE);
//                setTabSelect(0);
                mViewPager.setCurrentItem(0);
                break;
            case R.id.rl_tab_comment:
                tvTabDetail.setTextColor(Color.BLACK);
                tvTabComment.setTextColor(Color.RED);
                lineTabDetail.setVisibility(View.INVISIBLE);
                lineTabComment.setVisibility(View.VISIBLE);
//                setTabSelect(1);
                mViewPager.setCurrentItem(1);
                break;
        }
    }

    public void setTabSelect(int i) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        switch (i) {
            case 0:
                transaction.replace(R.id.frament, Fragment_Detail_GoodsDetail_DetailWeb.newInstance(mInfo.getData().getContent()));
                break;
            case 1:
                transaction.replace(R.id.frament, Fragment_Detail_DirectBuy_GoodsDetail_Comment.newInstance(mInfo.getData().getId() + ""));
                break;
        }
        transaction.commit();

    }

    private void setupViewPager() {

        ArrayList<BaseLazyFragment> mFragments = new ArrayList<>();
        fragment1 = Fragment_DirectBuy_GoodsDetail_DetailWeb.newInstance(mInfo.getData().getContent());
        Fragment_Detail_DirectBuy_GoodsDetail_Comment fragment2 = Fragment_Detail_DirectBuy_GoodsDetail_Comment.newInstance(mInfo.getData().getId() + "");
        mFragments.add(fragment1);
        mFragments.add(fragment2);

        BaseFragmentAdapter adapter =
                new BaseFragmentAdapter(getSupportFragmentManager(), mFragments);

        mViewPager.setAdapter(adapter);
    }

//    /**
//     * 商品规格
//     */
//    public void showBottomPop(View v, int check, String s) {
//
//        CheckInchPopWindow popWindow = new CheckInchPopWindow(this, mInfo, s, detailid, check, option);
//        popWindow.setData(check);
//        popWindow.showAsDropDown(v);
////        PopDetailSpecChoose popWindow = new PopDetailSpecChoose(mcontext,mInfo);
//
//    }

    private void ToPay(int typeid, int check) {
        Intent intent = new Intent(this, PayActivity.class);
        if (goodsItemBeen != null) {
//            showBottomPop(mcontext.getWindow().getDecorView(),check, "");
        } else {
//            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_ID, detailid);
//            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_NUM, num);
//            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_SPEC, spec);
//            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_COMMON_ID, common_id);
//            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_OPTION, option);
//            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_TYPEID, typeid);
//            startActivity(intent);
            ToFirmOrder(detailid);
        }
    }

    private void ToFirmOrder(String detailId) {
        //走确认订单的接口
//        Intent intent_address = new Intent(mcontext, BaseObject.class);
//        intent_address.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "确认订单");
        //直接支付的接口
        Intent intent_address = new Intent(mcontext, DirectBuyPayOrderActivity1.class);
        intent_address.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ID, detailId);
        intent_address.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_QTY, 1);
        startActivity(intent_address);
    }

    private void GetDetail(String id) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MAIN_DETAIL + "?id=" + id;
        MyLog.e("ddd地址", address);
        if (networkConnected) {
            HttpUtils.get(address, null, dataCallback);
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(mcontext, "网络未连接");
        }
    }
    DirectBuyGoodsDetailCallback dataCallback = new DirectBuyGoodsDetailCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
        }

        @Override
        public void onResponse(DirectBuyGoodsDetail response, int id) {
            if (response.getCode() == 0) {
                mInfo = response;
                setupViewPager();
                AddData(response);
                String price = response.getData().getPrice();
                shareurl = response.getData().getUrl();
                sharecontent = response.getData().getShare_content();
                sharethumb = response.getData().getThumb();
                //商品规格属性
//                        goodsItemBeen = response.getData().getGoods_item();

                ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);

            } else {
                noData.setVisibility(View.VISIBLE);
                noDataTv.setText(response.getMsg());
                noDataTv.setVisibility(View.VISIBLE);
            }
        }
    };

    private void AddData(DirectBuyGoodsDetail response) {
        if(response.getData().getStore()!=null) {
            bid = response.getData().getStore().getId();
        }
        goods_id = response.getData().getId();
//        setTabSelect(0);
//        initWebContent(response);
//        type = response.getData().getTypeid();
        detailid = response.getData().getId() + "";
        String price = response.getData().getPrice();
        String score = response.getData().getScore();
        singleMoney.setText("¥"+price);
        singleScore.setText(score+"积分");
        totalMoney.setText("¥"+price);
        totalScore.setText(score+"积分");
        String titleName = response.getData().getName();
        detailTitle.setText("                 " + titleName);


        CommonUtils.SetPriceViewHideOrVisible(singleMoney,goods_list_item_add,price);
//        if(fragment1.getActivity()==null){
//            setupViewPager();
//            ReleaseManager.printLog("fragment1.getActivity()","nullnull");
//        }

        fragment1.setTJ_List(response.getData().getTj_list());
//        if(response.getData().getTj_list()!=null){
//            adapter_like = new GridDirectBuyGoodsDetaillikeAdapt(mcontext, response.getData().getTj_list());
//            detailLikeGrid.setAdapter(adapter_like);
//            llLike.setVisibility(View.VISIBLE);
//        }else{
//            llLike.setVisibility(View.GONE);
//        }


        if (response.getData().getThumbs() != null && response.getData().getThumbs().size() > 0) {
            Banner.addAll(response.getData().getThumbs());
            adapter_banner.notifyDataSetChanged();
        } else {
            banner.setVisibility(View.GONE);
        }

        if (response.getData().getStore() != null) {
            storeMsg.setVisibility(View.VISIBLE);
            storeid = response.getData().getStore().getId();
            ObjectUtils.photo(mcontext, response.getData().getStore().getLogo(), storeLogo);
            String storename = response.getData().getStore().getName();
            SpannableString spannableString  = new SpannableString("本商品由" + storename + "提供及负责发货，并提供售后服务。");
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.RED);
            spannableString.setSpan(colorSpan, 4, 4+storename.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            storeName.setText(spannableString);
        } else {
            storeMsg.setVisibility(View.GONE);
        }

    }

//    private void initWebContent(DirectBuyGoodsDetail response) {
//        if (response.getData().getContent() != null && !response.getData().getContent().equals("")) {
//            nodata.setVisibility(View.GONE);
//            //宽度适应屏幕
//            String js = "<style>\n" +
//                    "img{\n" +
//                    " max-width:100%;\n" +
//                    "height:auto\n" +
//                    "}\n" +
//                    "</style>" + response.getData().getContent();
//            detailWebView.loadDataWithBaseURL(null, js, "text/html", "utf-8", null);
//
//        } else {
//            nodata.setVisibility(View.VISIBLE);
//        }
//
//    }

    /**
     * 获取大家都在
     * 团列表数据
     */

//    private void GetDataListData(String type) {
//
//        String address = ConstantsUrl.domain + ConstantsUrl.MAIN_LISTDATA + "?size=" + 8 + type;
//
//        HttpUtils.get(address, null, new MainListCallback() {
//
//            @Override
//            public void onError(Call call, Exception e, int id) {
//
//            }
//
//            @Override
//            public void onResponse(MainList response, int id) {
//                listdata.clear();
//                if (response.getData() != null) {
//                    listdata.addAll(response.getData().getList());
//                    adapter_like.notifyDataSetChanged();
//                }
//
//
//            }
//        });
//
//    }

//    class MyWebChromeClient extends WebChromeClient {
//        @Override
//        public void onProgressChanged(WebView view, int newProgress) {
//        }
//    }
//
//    class MyWebViewClient extends WebViewClient {
//        //拦截网址
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        detailWebView.getSettings().setJavaScriptEnabled(false);
    }
}
